<template>
    <div class="map-container">
        <div id="main" style="width: 100%; height: 100%;"></div>
    </div>
</template>

<script setup>
import * as echarts from "echarts/core";
// 修改导入语句
import { GeoComponent, VisualMapComponent, TooltipComponent } from 'echarts/components';

// 注册组件时添加tooltip
echarts.use([GeoComponent, CanvasRenderer, VisualMapComponent, TooltipComponent]);
import { CanvasRenderer } from 'echarts/renderers';
import { onMounted, onUnmounted, ref, watch } from "vue";
import { cloudeyeGetMap } from "@/api/dictionary.js"
// 添加props定义
const props = defineProps({
    mapData: {
        type: Array,
        default: () => []
    }
});
// 添加图表实例引用
const chartInstance = ref(null);

// 注册必要组件
echarts.use([GeoComponent, CanvasRenderer, VisualMapComponent]);

const emit = defineEmits(['xqMapClick'])
const alladcode = ref('') // 中文名对应的行政区划编码

onMounted(() => {
    chartInstance.value = echarts.init(
        document.getElementById('main')
    );
    initChart()
});
// 初始化
const initChart = async () => {
    alladcode.value = await getGeoJson('all.json')
    let chinaMap = await getGeoJson('100000_full.json')
    let formatChinaGeoJson = await formatJson(chinaMap)
    initEcharts(formatChinaGeoJson, '中华人民共和国')
}
//echarts绘图
const initEcharts = (geoJson, name) => {
    // 注册3D地图
    echarts.registerMap(name, geoJson)
    const option = generateMapOptions(props.mapData || [], name);
    // 下钻的时候地图大小设置,不设置会有部分地图超出屏幕
    const eightSizes = ['中华人民共和国', '山东省']
    option.geo.forEach((v) => {
        v.map = name
        v.layoutSize = eightSizes.indexOf(name) != -1 ? '180%' : '100%'
    })
    option.series[1].map = name
    option.series[1].layoutSize = eightSizes.indexOf(name) != -1 ? '180%' : '100%'

    chartInstance.value.clear()
    chartInstance.value.setOption(option)

    // 点击事件
    chartInstance.value.off('click')
    chartInstance.value.on('click', (params) => {
        mapClickfun(params, true)
    });
    // 窗口resize监听
    chartInstance.value.resizeHandler = () => chartInstance.value.resize();
    window.addEventListener('resize', chartInstance.value.resizeHandler);
}
// 地图点击事件
const mapClickfun = (params, onClick = false) => {
    let clickRegionCode = alladcode.value.filter((areaJson) => areaJson.name === params.name)[0].adcode
    if (onClick) {
        // 编码处理逻辑
        const codeValue = String(clickRegionCode).length === 6
            ? String(clickRegionCode).endsWith('0000')
                ? String(clickRegionCode).slice(0, 2)  // 省码：37
                : String(clickRegionCode).endsWith('00')
                    ? String(clickRegionCode).slice(0, 4) // 市码：3701
                    : String(clickRegionCode) // 区县码：370101
            : String(clickRegionCode);
        emit('xqMapClick', {
            name: params.name,
            regionCode: clickRegionCode + '000000',
            regionId: codeValue,
        })
    }
    // 没有区县的地级市,东莞,中山,儋州,三沙,嘉峪关, 这5个市比较特殊,没有下一级区县,在获取地图json官网接口可以看出来,中国,省,市,这三级的地图json的接口是 '行政区划+_full.json'的,而最后一级区县的地图json接口是 '行政区划+.json'.由于这5个地级市没有区县,所以他们就是最后一级,所以他们接口参数格式是'行政区划+.json'
    let adcodeArr = ['460400', '460300', '441900', '442000', '620200']
    let regJson = `${clickRegionCode}_full.json`
    if (params.name == '台湾省') {
        regJson = `${clickRegionCode}.json`
    }
    // 区县或者没有区县的地级市,行政区划最后两位不是00的就是最后一级,adcodeArr除外
    if (clickRegionCode.toString().slice(-2) != '00' || adcodeArr.includes(clickRegionCode.toString())) {
        regJson = `${clickRegionCode}.json`
    }
    // 调用地图Json数据
    getGeoJson(regJson).then(async (regionGeoJson) => {
        if (params.name == '中华人民共和国') {
            let formatChinaGeoJson = await formatJson(regionGeoJson)
            initEcharts(formatChinaGeoJson, '中华人民共和国')
        } else {
            initEcharts(regionGeoJson, params.name)
        }
    })
}
defineExpose({
    mapClickfun
});
// 地图JSON数据处理
const getGeoJson = async (jsonName) => {
    const msg = await cloudeyeGetMap(jsonName)
    return msg
}
// 南沙诸岛以缩略图展示
const formatJson = async (chinaGeoJson) => {
    chinaGeoJson.features.forEach((v) => {
        if (v.properties && v.properties.name == '海南省') {
            v.geometry.coordinates = v.geometry.coordinates.slice(0, 1)
        }
    })
    // 过滤掉海南诸岛边界线
    chinaGeoJson.features = chinaGeoJson.features.filter((item) => item.properties.adcode !== '100000_JD')
    return chinaGeoJson
}

// 新增配置生成方法
const generateMapOptions = (data, mapName) => {
    // 转换数据格式时添加value字段
    const regions = data.map(item => ({
        name: item.region,
        value: item.value,  // 传递数值字段
        itemStyle: {
            borderWidth: item.highlight ? 2 : 0.8
        }
    }));
    // 散点地图数据处理
    let currentData = props.mapData.map((item) => {
        return {
            name: item.region,
            value: [item.lng, item.lat, item.total_area || 0],
        }
    })
    return {
        series: [
            {
                type: 'effectScatter',
                zlevel: 3,
                coordinateSystem: 'geo',
                emphasis: {
                    itemStyle: {
                        color: 'aqua',
                        shadowColor: 'aqua'
                    },
                    label: {
                        show: true,
                        position: 'top',
                        color: '#fff',
                        formatter: (params) => {
                            return `{b|${params.name}:${params.value[2]}公顷}`;
                        },
                        rich: {
                            b: {
                                color: '#fff',
                                backgroundColor: {
                                    image: new URL('../../assets/dpsdtc.png', import.meta.url).href,
                                    repeat: 'no-repeat',
                                    width: 80,
                                    height: 5,
                                },
                                padding: [20, 30],
                                fontSize: 14,
                                align: 'center',
                                width: 80,
                                height: 5,
                            },
                        }
                    },
                },
                label: {
                    show: true,
                    position: 'top',
                    color: '#fff',
                    formatter: (params) => {
                        return `{b|${params.value[2]}公顷}`;
                    },
                    rich: {
                        b: {
                            color: '#fff',
                            padding: [0, 20],
                            fontSize: 14,
                            align: 'center',
                        },
                    }
                },
                data: currentData,
                symbol: 'circle',
                symbolSize: [20, 10],
                itemStyle: {
                    color: 'orange',
                    shadowBlur: 10,
                    shadowColor: 'orange',
                },
                effectType: 'ripple',
                showEffectOn: 'render', //emphasis移入显示动画，render一开始显示动画
                rippleEffect: {
                    scale: 5,
                    brushType: 'stroke',
                },
            },
            {
                name: mapName,
                type: 'map',
                map: mapName,
                aspectScale: 1,
                layoutSize: '100%',  // 保持与geo布局一致
                layoutCenter: ['50%', '50%'],
                zoom: 0.9,  // 缩放比例同步
                label: {
                    show: false,  // 关闭省份名称显示
                    color: '#fff'
                },
                data: regions, // 这里接收处理后的regions数据
                itemStyle: {
                    // 每块的样式
                    areaColor: {
                        type: 'linear',
                        x: 1200,
                        y: 0,
                        x2: 0,
                        y2: 0,
                        colorStops: [
                            {
                                offset: 0,
                                color: 'rgba(3,27,78,0.75)',
                            },
                            {
                                offset: 1,
                                color: 'rgba(58,149,253,0.75)',
                            },
                        ],
                        global: true, // 缺省为 false
                    },
                    borderColor: '#c0f3fb',
                    borderWidth: 0.8,
                },
                emphasis: {
                    label: {
                        show: true,
                        color: '#fff'
                    },
                    itemStyle: {
                        show: false,
                        color: '#fff',
                        areaColor: 'rgba(0,254,233,0.6)',
                    },
                }
            },
        ],
        geo: [
            // 主地图层（使用动态数据）
            {
                map: mapName,
                regions,
                aspectScale: 1,
                zoom: 0.9,
                layoutCenter: ['50%', '50%'],
                layoutSize: '100%',
                show: true,
                roam: false,
                label: {
                    show: false,  // 开启省份名称显示
                    color: 'rgba(255,255,255,0.8)',  // 半透明白色
                    fontSize: 12,
                },
                itemStyle: {
                    // 每块的样式
                    areaColor: {
                        type: 'linear',
                        x: 1200,
                        y: 0,
                        x2: 0,
                        y2: 0,
                        colorStops: [
                            {
                                offset: 0,
                                color: 'rgba(3,27,78,0.75)',
                            },
                            {
                                offset: 1,
                                color: 'rgba(58,149,253,0.75)',
                            },
                        ],
                        global: true, // 缺省为 false
                    },
                    borderColor: '#c0f3fb',
                    borderWidth: 0.8,
                },
                emphasis: {
                    itemStyle: {
                        show: true, // 鼠标悬浮时显示
                        borderWidth: 2,  // 悬浮时的边框宽度
                        borderColor: '#3B7BD5',  // 悬浮时的边框颜色
                        color: '#fff',
                        areaColor: 'rgba(0,254,233,0.6)',
                    },
                    label: {
                        show: true,
                        color: '#fff',
                    },
                },
            },// 重影
            {
                type: 'map',
                map: mapName,
                zlevel: -1,
                aspectScale: 1,
                zoom: 0.9,
                layoutCenter: ['50%', '50.5%'],
                layoutSize: '100%',
                roam: false,
                silent: true,
                itemStyle: {
                    borderWidth: 1,
                    borderColor: 'rgba(58,149,253,0.8)',
                    shadowColor: 'rgba(172, 122, 255,0.5)',
                    shadowOffsetY: 5,
                    shadowBlur: 15,
                    areaColor: 'rgba(5,21,35,0.1)',
                },
            },
            {
                type: 'map',
                map: mapName,
                zlevel: -2,
                aspectScale: 1,
                zoom: 0.9,
                layoutCenter: ['50%', '51%'],
                layoutSize: '100%',
                roam: false,
                silent: true,
                itemStyle: {
                    borderWidth: 1,
                    borderColor: 'rgba(58,149,253,0.6)',
                    shadowColor: 'rgba(65, 214, 255,0.6)',
                    shadowOffsetY: 5,
                    shadowBlur: 15,
                    areaColor: 'rgba(5,21,35,0.1)',
                },
            },
            {
                type: 'map',
                map: mapName,
                zlevel: -3,
                aspectScale: 1,
                zoom: 0.9,
                layoutCenter: ['50%', '51.5%'],
                layoutSize: '100%',
                roam: false,
                silent: true,
                itemStyle: {
                    borderWidth: 1,
                    borderColor: 'rgba(58,149,253,0.4)',
                    shadowColor: 'rgba(29, 111, 165,1)',
                    shadowOffsetY: 15,
                    shadowBlur: 10,
                    areaColor: 'rgba(5,21,35,0.1)',
                },
            },
            {
                type: 'map',
                map: mapName,
                zlevel: -4,
                aspectScale: 1,
                zoom: 0.9,
                layoutCenter: ['50%', '52%'],
                layoutSize: '100%',
                roam: false,
                silent: true,
                itemStyle: {
                    borderWidth: 5,
                    borderColor: 'rgba(5,9,57,0.8)',
                    shadowColor: 'rgba(29, 111, 165,0.8)',
                    shadowOffsetY: 15,
                    shadowBlur: 10,
                    areaColor: 'rgba(5,21,35,0.1)',
                },
            },
        ],
    };
}

// 添加数据监听
watch(() => props.mapData, (newVal) => {
    if (chartInstance.value) {
        // 增加空值检查和属性验证
        if (chartInstance.value._model?.option?.geo?.[0]?.map) {
            const mapName = chartInstance.value._model.option.geo[0].map;
            const option = generateMapOptions(newVal, mapName);
            try {
                // 下钻的时候地图大小设置,不设置会有部分地图超出屏幕
                const eightSizes = ['中华人民共和国', '山东省']
                option.geo.forEach((v) => {
                    v.map = mapName
                    v.layoutSize = eightSizes.indexOf(mapName) != -1 ? '180%' : '100%'
                })
                option.series[1].map = mapName
                option.series[1].layoutSize = eightSizes.indexOf(mapName) != -1 ? '180%' : '100%'
                chartInstance.value.setOption(option, true);
                chartInstance.value.resize();
            } catch (e) {
                console.error('图表配置更新失败:', e);
            }
        }
    }
}, {
    deep: true,
    immediate: true
});

onUnmounted(() => {
    if (chartInstance.value) {
        // 添加更彻底的清理逻辑
        chartInstance.value.off('click');
        chartInstance.value.dispose();
        chartInstance.value = null;  // 清除引用
        window.removeEventListener('resize', chartInstance.value?.resizeHandler);
    }
});
</script>

<style scoped>
.map-container {
    width: 100%;
    height: 100%;
    position: relative;
}

#main {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
}
</style>
